/********************************************************************************************
** Copyright � 2011 Nokia Corporation. All rights reserved.
** Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation.
** Java and all Java-based marks are trademarks or registered trademarks of
** Sun Microsystems, Inc. Other product and company names mentioned herein may be
** trademarks or trade names of their respective owners.
**
** Subject to the conditions below, you may, without charge:
**
** �  Use, copy, modify and/or merge copies of this software and
**    associated content and documentation files (the �Software�)
**
** �  Publish, distribute, sub-licence and/or sell new software
**    derived from or incorporating the Software.
**
** Some of the documentation, content and/or software maybe licensed under open source
** software or other licenses.  To the extent such documentation, content and/or
** software are included, licenses and/or other terms and conditions shall apply
** in addition and/or instead of this notice. The exact terms of the licenses, disclaimers,
** acknowledgements and notices are reproduced in the materials provided.
**
** This file, unmodified, shall be included with all copies or substantial portions
** of the Software that are distributed in source code form.
**
** The Software cannot constitute the primary value of any new software derived
** from or incorporating the Software.
**
** Any person dealing with the Software shall not misrepresent the source of the Software.
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
** INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
** PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
** HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
** OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
** SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
********************************************************************************************/
import Qt 4.7

import QtMobility.contacts 1.1
import "DCDataClasses.js" as DCDATA


Dialog {
    id: memberselctiondlg
    width: 400
    height: 400
    label:  "CarPool Members"
    z: 4


    property string datacloudurl: ""
    property string username: ""
    property string password: ""
    property string ownerkarpoid: ""
    property string carpoolkarpoid: ""

    property int labelWidth: 120

    property int selectmemberind: -1
    property int removememberind: -1

    signal membersSelected(string memberslist)

    onOk:
    {
        var membersstr = new Array()
        for (var i=0;i<selectedmembers.count;i++)
        {
            var mem = selectedmembers.get(i)
            membersstr[i]=mem
        }

        memberselctiondlg.membersSelected(JSON.stringify(membersstr))

        selectedmembers.clear();
    }


    Text {
        id: selectmembertextid
        width: labelWidth
        text: "Select member:"
        anchors.left: parent.left
        anchors.leftMargin: 10
        anchors.top: memberselctiondlg.titlerect.bottom
        anchors.topMargin: 5
        font.pixelSize: 16
    }





    Rectangle {
        id: itemsrect
        width: parent.width
        height: 4*16
        clip: true
        border.color: "#000000"
        anchors.top: selectmembertextid.bottom
        anchors.topMargin: 5
        anchors.left: parent.left
        anchors.leftMargin: 10
        anchors.right: parent.right
        anchors.rightMargin: 10

        visible:  true

        Component {
            id: selectmemberlistItem
            Rectangle {
                id: itemrect
                color: "white"
                clip: true
                x: 1
                y: 1

                property string itemlabel: (lastname + ", " + firstname + "  - " + phone + ", " + hometown)
                property int itemindex: index
                property bool isselected: selected

                width: parent.width - 2
                height: 22

                MouseArea {
                    id: mousearea
                    anchors.fill: parent
                    hoverEnabled: true

                    onClicked:
                    {
                        memberselctiondlg.selectmemberind = itemrect.itemindex
                    }

                    states: [
                    State {
                        id: stateSelected
                        name: "isselected"; when: itemrect.isselected
                        PropertyChanges { target: itemrect; color: "yellow";  }
                    },
                    State {
                        id: stateHovered
                        name: "hovered"; when: mousearea.containsMouse
                        PropertyChanges { target: itemrect; color: "yellow"; }
                    }
                    ]

                }

                Column {
                    Text {
                    font.pixelSize: 16
                    text: itemlabel
                    }
                }
            }
        }

        ListView {
            id: itemslist
            model: selectablemembers
            delegate: selectmemberlistItem
            anchors.fill: parent
            snapMode: ListView.SnapOneItem
        }
    }

    ListModel
    {
        id: selectablemembers
    }

    function getdcuserscb(response)
    {

        messagebox.visible = false
        console.log("getdcuserscb" + JSON.stringify(response))

        try
        {
            for (var i=0;i<response.userlist.length;i++)
            {
                selectablemembers.append({"karpoid":response.userlist[i].karpoid,
                                 "firstname":response.userlist[i].firstname,
                                 "lastname":response.userlist[i].lastname,
                                 "hometown":response.userlist[i].hometown,
                                 "phone":response.userlist[i].phone,
                                 "selected":false})
            }
        }
        catch (e)
        {
            console.log("getdcuserscb exception: " + e)
        }
    }

    // ----------- PUSH BUTTONS ------------------------

    PushButton
    {
        id: selectnewmemberid
        label: "Select member"
        width: 150
        anchors.left: parent.left
        anchors.leftMargin: 10
        anchors.top: itemsrect.bottom
        anchors.topMargin: 5

        onButtonpressed:
        {

           if (memberselctiondlg.selectmemberind > -1 &&
                   selectablemembers.count > 0 &&
                    selectablemembers.count > memberselctiondlg.selectmemberind)
           {
               var member = selectablemembers.get(memberselctiondlg.selectmemberind);
               selectedmembers.append({"karpoid":member.karpoid,
                                "firstname":member.firstname,
                                "lastname":member.lastname,
                                "hometown":member.hometown,
                                "phone":member.phone,
                                "selected":false});

               memberselctiondlg.selectmemberind = -1
           }
        }

    }

    PushButton
    {
        id: removememberid
        label: "Remove member"
        width: 150
        anchors.right: parent.right
        anchors.rightMargin: 10
        anchors.top: itemsrect.bottom
        anchors.topMargin: 5

        onButtonpressed:
        {

           if (memberselctiondlg.removememberind > -1 &&
                   selectedmembers.count > 0 &&
                    selectedmembers.count > memberselctiondlg.removememberind)
           {
               selectedmembers.remove(memberselctiondlg.removememberind)
               memberselctiondlg.removememberind = -1
           }
        }

    }

    // ---------- SELECTED MEMBERS ---------------------

    Text {
        id: selectedmembertextid
        width: labelWidth
        text: "Selected members:"
        anchors.left: parent.left
        anchors.leftMargin: 10
        anchors.top: selectnewmemberid.bottom
        anchors.topMargin: 5
        font.pixelSize: 16
    }




    Rectangle {
        id: selectedmemberitemsrect
        width: parent.width
        height: 4*16
        clip: true
        border.color: "#000000"
        anchors.top: selectedmembertextid.bottom
        anchors.topMargin: 5
        anchors.left: parent.left
        anchors.leftMargin: 10
        anchors.right: parent.right
        anchors.rightMargin: 10

        visible:  true

        Component {
            id: selectedmemberlistItem
            Rectangle {
                id: itemrect
                color: "white"
                clip: true
                x: 1
                y: 1

                property string itemlabel: (lastname + ", " + firstname + "  - " + phone + ", " + hometown)
                property int itemindex: index
                property bool isselected: selected

                width: parent.width - 2
                height: 22

                MouseArea {
                    id: mousearea
                    anchors.fill: parent
                    hoverEnabled: true

                    onClicked:
                    {

                        memberselctiondlg.removememberind = itemrect.itemindex
                    }

                    states: [
                    State {
                        id: stateSelected
                        name: "isselected"; when: itemrect.isselected
                        PropertyChanges { target: itemrect; color: "yellow";  }
                    },
                    State {
                        id: stateHovered
                        name: "hovered"; when: mousearea.containsMouse
                        PropertyChanges { target: itemrect; color: "yellow"; }
                    }
                    ]
                }

                Text {
                    anchors.verticalCenter: parent.verticalCenter
                    font.pixelSize: 16
                    text: itemlabel
                }

            }
        }


        ListView {
            id: selectedmembersitemslist
            model: selectedmembers
            delegate: selectedmemberlistItem
            anchors.fill: parent
            snapMode: ListView.SnapOneItem
        }
    }

    ListModel
    {
        id: selectedmembers
    }



    onMenuSelection:
    {
        if (selectionlabel == "Contacts...")
        {
            selectablemembers.clear();

            console.log("contacts: " + contactModel.contacts.length)
            var contactlist = contactModel.contacts;
            for (var c = 0; c < contactlist.length; c++)
            {
                if ( (contactlist[c].name.firstName != "" || contactlist[c].name.lastName != "") && contactlist[c].phoneNumber.number != "")
                {

                    selectablemembers.append({"karpoid":"0",
                                     "firstname":contactlist[c].name.firstName,
                                     "lastname":contactlist[c].name.lastName,
                                     "hometown":contactlist[c].address.locality,
                                     "phone":contactlist[c].phoneNumber.number,
                                     "selected":false})
                }

            }


        }
        else if (selectionlabel == "Members...")
        {
            messagebox.text = "Get the Carpool members..."
            messagebox.show("")

            selectablemembers.clear();

            var userlist = new DCDATA.DCUserList()
            userlist.karpoid = "1*"
            userlist.phoneRequired = true
            userlist.firstnameRequired = true
            userlist.lastnameRequired = true
            userlist.hometownRequired = false

            DCDATA.send(userlist, datacloudurl, "getdatacloudusers", memberselctiondlg.getdcuserscb)

        }
    }

    Component.onCompleted:
    {
        var arr = ["Contacts...", "Members..."]
        memberselctiondlg.addMenuItems(arr,true)

    }


    MessageBox
    {
        id: messagebox
    }


    ContactModel {
        id: contactModel


        Component.onCompleted : {


            //MANAGER: simulator
            //MANAGER: memory
            //MANAGER: invalid

            // MANAGER: symbian

            for (var i = 0; i < contactModel.availableManagers.length; i++)
            {
                //console.log("MANAGER: " + contactModel.availableManagers[i])
                if (contactModel.availableManagers[i] == "symbian")
                {
                    manager = "symbian"
                }
            }

        }

    }




}
